package com.yuanchu.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @version: 1.0
 * @Author: adan
 * @description:
 * @date: 2024-02-17 23:28
 */

public class GoodsFormatUtils {

    /**
     * 解析商品属性
     * @param props
     * @return
     */
    public static List<Map<String, Object>> formatGoodsProps(String props) {
        // 解析JSON数组到List<Map<String, Object>>
        JSONArray jsonArray = JSONArray.parseArray(props);
        if (StringUtils.isEmpty(props)){
            return Collections.emptyList();
        }
        List<Map<String, Object>> specItemsAsMaps = new ArrayList<>();

        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            Map<String, Object> itemMap = jsonObject.toJavaObject(Map.class);
            // 将嵌套的对象也转为Map
            Map<String, Object> groupMap = ((JSONObject) itemMap.get("group")).toJavaObject(Map.class);
            Map<String, Object> valueMap = ((JSONObject) itemMap.get("value")).toJavaObject(Map.class);

            // 将group和value替换为它们对应的Map对象
            itemMap.put("group", groupMap);
            itemMap.put("value", valueMap);

            specItemsAsMaps.add(itemMap);
        }

        return specItemsAsMaps;
    }
}
